﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace Lon.Util
{

    public class Win32Api
    {
        public const int WM_COPYDATA = 0x004A;

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern int SendMessage(IntPtr hWnd, int wMsg, int wParm, int lParam);

        [DllImport("User32.dll", CharSet = CharSet.None)]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("User32.dll", CharSet = CharSet.None)]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        public extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImportAttribute("Kernel32.dll")]
        public static extern void GetLocalTime(SystemTime st);
      
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool SetLocalTime(ref SystemTime systemTime);

        [DllImport("Kernel32.dll")]
        public static extern int GetLastError();

        [DllImport("Kernel32.dll")]
        public extern static bool GetSystemTimes(out long lpIdleTime, out long lpKernelTime, out long lpUserTime);

        #region 报警声音驱动
        [DllImport("kernel32.dll")]
        public static extern bool Beep(int freq, int duration);
        //警铃驱动
        [DllImport("PortIO32.dll", EntryPoint = "Out32")]
        public static extern void Output(int adress, byte value);
        [DllImport("PortIO32.dll", EntryPoint = "Inp32")]
        public static extern int Input(int adress);
        #endregion

        /// <summary>
        /// 通过 SendMessage 向指定句柄发送数据
        /// </summary>
        /// <param name="hWnd"> 接收方的窗口句柄 </param>
        /// <param name="dwData"> 附加数据< /param>
        /// <param name="lpdata"> 发送的数据 </param>
        public static int SendCopyData(IntPtr hWnd, int dwData, byte[] lpdata)
        {
            COPYDATASTRUCT cds = new COPYDATASTRUCT();

            cds.dwData = (IntPtr)dwData;

            cds.cbData = lpdata.Length;

            cds.lpData = Marshal.AllocHGlobal(lpdata.Length);

            Marshal.Copy(lpdata, 0, cds.lpData, lpdata.Length);

            IntPtr lParam = Marshal.AllocHGlobal(Marshal.SizeOf(cds));

            Marshal.StructureToPtr(cds, lParam, true);


            int result = 0;

            try
            {
                result = SendMessage(hWnd, WM_COPYDATA, 0, (int)lParam);

            }
            finally
            {
                Marshal.FreeHGlobal(cds.lpData);

                Marshal.DestroyStructure(lParam, typeof(COPYDATASTRUCT));

                Marshal.FreeHGlobal(lParam);

            }

            return result;

        }

        /// <summary>
        /// 获取消息类型为 WM_COPYDATA 中的数据
        /// </summary>
        /// <param name="m"></param>
        /// <param name="dwData"> 附加数据 </param>
        /// <param name="lpdata"> 接收到的发送数据 </param>
        public static void ReceivCopyData(ref System.Windows.Forms.Message m, out int dwData, out byte[] lpdata)
        {
            COPYDATASTRUCT cds = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));

            dwData = cds.dwData.ToInt32();

            lpdata = new byte[cds.cbData];

            Marshal.Copy(cds.lpData, lpdata, 0, cds.cbData);

            m.Result = (IntPtr)0;

        }

        public static bool SetLocalTime(DateTime dt)
        {
            var st = new SystemTime();
            st.wYear = (short)dt.Year;
            st.wMonth = (short)dt.Month;
            st.wDay = (short)dt.Day;
            st.wHour = (short)dt.Hour;
            st.wMinute = (short)dt.Minute;
            st.wSecond = (short)dt.Second;
            //st.wMilliseconds = (ushort)dt.Millisecond;
            st.wDayOfWeek = (short)dt.DayOfWeek;
            try
            {
                return Win32Api.SetLocalTime(ref st);

            }
            catch (Exception ex)
            {
                NetDebugConsole.WriteLine(ex.Message + ex.StackTrace);
            }

            return true;

        }
        /// <summary>
        /// 查找指定进程的窗口句柄 
        /// </summary>
        /// <param name="processName"></param>
        /// <returns></returns>
        public static IntPtr GetProcessHandle(string processName)
        {
            //进程是否正在运行
            //string vshostName = string.Format("{0}.vshost", processName);
            string vshostName = string.Format("{0}", processName);

            IntPtr hWnd = IntPtr.Zero;
            Process[] processOnComputer = Process.GetProcesses();
            foreach (System.Diagnostics.Process p in processOnComputer)
            {
                if (p.ProcessName.Equals(processName) || p.ProcessName.Equals(vshostName))
                {
                    hWnd = p.MainWindowHandle;
                    break;
                }
            }

            return hWnd;
        }

        public static void SetIOCardON()
        {
            Output(0x2A8, 0xff);
        }
        public static void SetIOCardOFF()
        {
            Output(0x2A8, 0x00);
        }
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct SystemTime
    {

        [MarshalAs(UnmanagedType.U2)]

        public short wYear;

        [MarshalAs(UnmanagedType.U2)]

        public short wMonth;

        [MarshalAs(UnmanagedType.U2)]

        public short wDayOfWeek;

        [MarshalAs(UnmanagedType.U2)]

        public short wDay;

        [MarshalAs(UnmanagedType.U2)]

        public short wHour;

        [MarshalAs(UnmanagedType.U2)]

        public short wMinute;

        [MarshalAs(UnmanagedType.U2)]

        public short wSecond;

        [MarshalAs(UnmanagedType.U2)]

        public short wMilliseconds;

    }

    /// <summary>
    /// 发送 WM_COPYDATA 消息的数据结构体
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public struct COPYDATASTRUCT
    {
        /// <summary>
        /// 用户自定义数据
        /// </summary>
        public IntPtr dwData;

        /// <summary>
        /// 数据长度
        /// </summary>
        public int cbData;

        /// <summary>
        /// 数据地址指针
        /// </summary>
        public IntPtr lpData;


    }




}
